from elasticsearch import Elasticsearch  
  
# 使用elasticsearch库创建Elasticsearch客户端实例  
es = Elasticsearch([{'host': '192.168.80.35', 'port': 9200, 'scheme': 'http'}])  
  
def search_and_save_results(question, year1, year2):
    size=100
    save_path='/home/zhengzhenzhuang/liujian/project/policy-model/data/name.txt'
    index_name='file_index'
    # 构建搜索查询
    query = {
        "query": {
            "bool": {
                "must": [
                    {"match": {"name": question}}  # 假设您要搜索的字段是'name'
                ]
            }
        },
        "size": size  # 设置返回结果的数量，可以根据需要调整
    }

    # 添加年份过滤条件（如果有）
    if year1 is not None and year2 is not None:
        range_query = {
            "range": {
                "year": {
                    "gte": year1,
                    "lte": year2
                }
            }
        }
        query["query"]["bool"].setdefault("filter", []).append(range_query)

    # 执行搜索
    results = es.search(index=index_name, body=query)

    # 提取并保存结果（如果需要）
    if save_path:
        contents = [hit['_source']['content'] for hit in results['hits']['hits']]
        with open(save_path, 'w', encoding='utf-8') as f:
            for i, content in enumerate(contents):
                if i < len(contents) - 1:
                    f.write(content + '\n'+'-----\n')
                else:
                    f.write(content)
        #print(f"相关文件名已保存到'{save_path}'")
    else:
        return results  # 如果不需要保存，则直接返回搜索结果



def search(question, year1, year2):
    index_name='file_index'
    query = {
        "query": {
            "bool": {
                "must": [
                    {"match": {"name": question}}  # 假设您要搜索的字段是'name'
                ]
            }
        }
    }

    # 添加年份过滤条件（如果有）
    if year1 is not None and year2 is not None:
        range_query = {
            "range": {
                "year": {
                    "gte": year1,
                    "lte": year2
                }
            }
        }
        query["query"]["bool"].setdefault("filter", []).append(range_query)

    # 执行搜索
    results = es.search(index=index_name, body=query)
      # 提取搜索结果中的content字段
    # 提取第一个搜索结果中的 content 和 count 字段
    if results['hits']['hits']:
        source = results['hits']['hits'][0]['_source']
        content = source.get('content', '')
        count = source.get('count', None)

        # 如果 count 字段大于 32000，就截取 content 中的前 32000 个字符
        if count is not None and count > 32000:
            content = content[:32000]

        return content